<template>
  <div id="threeBox"></div>
</template>
<script setup>
import { getCurrentInstance, onMounted } from "vue";

let { proxy } = getCurrentInstance();
let THREE = proxy.$THREE;


onMounted(() => {
  //创建场景
  let scene = new THREE.Scene();

  //创建照相机
  let camera = new THREE.PerspectiveCamera(45,window.innerWidth / window.innerHeight, 0.1,2000);
  camera.position.x = -30;
  camera.position.y = 40;
  camera.position.z = 30;
  camera.lookAt(scene.position); //将相机指向场景

  //创建渲染器 (画布)
  let renderer = new THREE.WebGLRenderer();
  renderer.setClearColor(0xeeeeee); //canvas画布颜色
  renderer.setSize(window.innerWidth, window.innerHeight); //canvas 画布大小
  renderer.shadowMap.enabled = true; //让渲染器支持投影

  plane(scene); //地面
  cube(scene); //立方体
  point(scene); //灯光

  // 将这个canvas元素插入到 html中
  document.getElementById("threeBox").appendChild(renderer.domElement);
  renderer.render(scene, camera);

  let controls = new OrbitControls(camera, renderer.domElement);
  controls.addEventListener("change", () => {
    renderer.render(scene, camera);
  });
});
function cube(scene) {
  let cubeGeometry = new THREE.BoxGeometry(4, 4, 4); //长宽高
  let cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 }); //材质颜色
  let cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
  cube.position.x = 3; //三轴的位置
  cube.position.y = 8;
  cube.position.z = 3;
  scene.add(cube);
  cube.castShadow = true; //立方体投影
}



function point(scene) {
  let point = new THREE.SpotLight(0xffffff); //设置灯光的颜色
  point.position.set(80, 100, 80); //点光源位置
  point.angle = Math.PI / 10; //设置投影的程度
  point.shadow.mapSize.set(1024, 1024);
  scene.add(point);
  point.castShadow = true; //灯光投影
}

function plane(scene) {  // 创建地面的大小
  let planeGeometry = new THREE.PlaneGeometry(60, 20);   //地面的材质，宽高
  let planeMaterial = new THREE.MeshStandardMaterial({ color: 0x999999 });  // 创建地面
  let plane = new THREE.Mesh(planeGeometry, planeMaterial); // 设置地面的位置
  plane.rotation.x = -0.5 * Math.PI;
  plane.position.x = 15;
  plane.position.y = 0;
  plane.position.z = 0;
  scene.add(plane);  //将地面添加到坐标轴中
  plane.receiveShadow = true; //地面被投影
}
</script>